package com.jci.vsd.activity.enterprise;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jci.vsd.R;
import com.jci.vsd.activity.BaseActivity;
import com.jci.vsd.activity.LoginActivity;
import com.jci.vsd.adapter.enterprise.MembersManagerAdapter;
import com.jci.vsd.bean.UserBean;
import com.jci.vsd.bean.enterprise.AjustMembersBean;
import com.jci.vsd.bean.enterprise.MembersBean;
import com.jci.vsd.constant.MySpEdit;
import com.jci.vsd.data.UserData;
import com.jci.vsd.network.control.MembersManageControl;
import com.jci.vsd.observer.CommonDialogObserver;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.utils.TimePickerUtils;
import com.jci.vsd.view.widget.SimpleToast;
import com.jci.vsd.view.widget.treelist.TreeMenuBaseAdapter;
import com.jci.vsd.view.widget.treelist.bean.Node;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;

/**
 * Created by liqing on 18/6/29.
 * （主管类型）成员管理
 */

public class MembsersByDepartmentActivity extends BaseActivity {


    private static final int REQUEST_CODE_DEPARTMENT = 1111;
    @BindView(R.id.lv_members)

    ListView lvMembers;
    private MembersManagerAdapter<MembersBean> adapter;
    private List<MembersBean> mData;//所有成员集合

    private Dialog dialog;
    private View inflate;
    private TextView cancel;

    private Context context;
    private TextView tvAjust;
    private TextView tvDelete;
    private MembersBean selectOperateBean;//选中的人员
    private List<MembersBean> departmentList;//部门集合


    @BindView(R.id.button_back)
    ImageButton backBtn;
    @BindView(R.id.textview_title)
    TextView titleTxt;

    private String dptId;//部门Id
    private String userId;
    private String departName;//人员部门

    private MySpEdit prefs;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_members_manage);
        context = MembsersByDepartmentActivity.this;
        mData = new ArrayList<>();
        departmentList = new ArrayList<>();
        prefs = MySpEdit.getInstance();
        dptId = prefs.getDepartmentId();
        userId = prefs.getUserId();

        UserBean userBean = UserData.getUserInfo();
        if (userBean != null) {
            departName = userBean.getDepart();

        }
        initViewEvent();
        loadData();

    }


    private void initTreeMemberAdapter() {
        try {
            adapter = new MembersManagerAdapter<>(lvMembers, this, mData, 0);
            //  adapter.setListExpand(false);
            adapter.setTreeNodeClickListener(new TreeMenuBaseAdapter.OnTreeNodeClickListener() {
                @Override
                public void onNodeClick(Node node, int position) {
//
////                    Loger.e("---node--");
//                    if (node.getChildrenNodes().size() == 0) {
//                        // showDialog();
//                        //  SimpleToast.toastMessage("node－－", Toast.LENGTH_SHORT);
//                    }

                    adapter.setCurrentPosition(position, node.isExpand());
                    adapter.notifyDataSetChanged();
                }

            });

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        lvMembers.setAdapter(adapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_DEPARTMENT) {

            }

        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_select_company:
                //调整部门对话框
                showSingleChoiceDialog();
                dialog.dismiss();
                break;
            case R.id.tv_register_company:
                //从本公司删除成员
                deleteMember(selectOperateBean);
                dialog.dismiss();
                break;
            case R.id.btn_cancel:
                dialog.dismiss();
                break;
            default:
                break;
        }
    }

    String[] items = new String[]{};

//调整部门对话框
    private void showSingleChoiceDialog() {

        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("单选对话框").setIcon(R.drawable.ic_image)
                .setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Loger.e("choose-whitch--" + which);
                        AjustMembersBean ajustMembersBean = new AjustMembersBean();

                        ajustMembersBean.setDpt(Integer.valueOf(departmentList.get(which).getId()));
                        ajustMembersBean.setId(Integer.valueOf(selectOperateBean.getId()));
                        Loger.e("dptId=" + departmentList.get(which).getId());
                        Loger.e("ajustPersonid=" + selectOperateBean.getId());
                        ajust(ajustMembersBean);
                        dialog.dismiss();

                    }
                }).create();
        dialog.show();

    }

    @Override
    protected void initViewEvent() {
        backBtn.setOnClickListener(this);
        titleTxt.setText(getResources().getString(R.string.members_manage));
    }


    //加载MemberBean
    private void loadData() {
        Observable<List<MembersBean>> observable = new MembersManageControl().getMembers();
        CommonDialogObserver<List<MembersBean>> observer = new CommonDialogObserver<List<MembersBean>>(this) {
            @Override
            public void onNext(List<MembersBean> beanList) {
                super.onNext(beanList);

                mData.clear();
                departmentList.clear();

                for (int i = 0; i < beanList.size(); i++) {

                    Loger.e("--- tree name" + beanList.get(i).getName());
                    MembersBean bean = beanList.get(i);
                    String beanId = bean.getUid();
                    if (!TextUtils.isEmpty(beanId)) {
                        if (beanId.equals(userId)) {
                            //  找到部门主管  以及 部门id
                            dptId = bean.getPid();
                            prefs.setDepartmentId(dptId);
                        }
                    }

                    //找到部门名称
                    if (bean.getPid().equals("0") && bean.getDpt().equals(dptId)) {
                        //加入部门集合 id =229
                        departmentList.add(beanList.get(i));
                    }
                    //部门成员
                    if (!bean.getPid().equals("0") && bean.getPid().equals(dptId)) {
                        //加入部门集合 id =229
                        departmentList.add(beanList.get(i));
                    }


                }
                // mData.addAll(beanList);
                mData.addAll(departmentList);
                if (mData.size() != 0) {
                    initTreeMemberAdapter();
                } else {
                    SimpleToast.toastMessage("暂无部门成员信息", Toast.LENGTH_SHORT);
                }


            }


            @Override
            public void onError(Throwable t) {
                super.onError(t);
            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, MembsersByDepartmentActivity.this);
    }

    //delete members

    private void deleteMember(MembersBean membersBean) {
        Observable<Boolean> observable = new MembersManageControl().deleteMember(membersBean);
        CommonDialogObserver<Boolean> observer = new CommonDialogObserver<Boolean>(this) {
            @Override
            public void onNext(Boolean aBoolean) {
                super.onNext(aBoolean);
                if (aBoolean) {
                    SimpleToast.toastMessage("删除成功", Toast.LENGTH_LONG);
                    loadData();
                } else {
                    SimpleToast.toastMessage("删除失败，请重试！", Toast.LENGTH_LONG);
                }
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, MembsersByDepartmentActivity.this);
    }

    //调整到新部门 （ 新部门新增成员，就部门减一人）

    private void ajust(AjustMembersBean requestBean) {
        Observable<Boolean> observable = new MembersManageControl().ajustMember(requestBean);
        CommonDialogObserver<Boolean> observer = new CommonDialogObserver<Boolean>(this) {
            @Override
            public void onNext(Boolean aBoolean) {
                super.onNext(aBoolean);
                if (aBoolean) {
                    SimpleToast.toastMessage("操作成功", Toast.LENGTH_LONG);
                    loadData();
                } else {
                    SimpleToast.toastMessage("操作失败，请重试！", Toast.LENGTH_LONG);
                }
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);

                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_SHORT);
                    exit();
                    toActivity(LoginActivity.class);
                }
            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, MembsersByDepartmentActivity.this);
    }


}
